package com.twotiger.and.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import app.twotiger.p2p.R;
import app.twotiger.p2p.R.color;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.BitmapUtils;
import com.twotiger.and.Constants;
import com.twotiger.and.TwoTigerApp;
import com.twotiger.and.activity.base.BaseFragment;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.current.CurrentHost;
import com.twotiger.and.activity.current.CurrentInputAmountPage;
import com.twotiger.and.activity.project.InverstInputAmountPage;
import com.twotiger.and.activity.project.ProjectDetailPage;
import com.twotiger.and.activity.user.LoginPage;
import com.twotiger.and.adapter.ImagePagerAdapter;
import com.twotiger.and.adapter.NoticeAdapter;
import com.twotiger.and.bean.Banner;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.BroswerUrl;
import com.twotiger.and.bean.ConstantDataUnit;
import com.twotiger.and.bean.CurrentProject;
import com.twotiger.and.bean.DataList;
import com.twotiger.and.bean.Notice;
import com.twotiger.and.bean.Order;
import com.twotiger.and.bean.PlatInfo;
import com.twotiger.and.bean.PlatInfoOne;
import com.twotiger.and.bean.PlatInfoTwo;
import com.twotiger.and.bean.ProjectDetail;
import com.twotiger.and.bean.ProjectdetailData;
import com.twotiger.and.bean.TjRegisteResult;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.ListUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.TimeUtils;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.URLUtil;
import com.twotiger.and.util.ViewUtils;
import com.view.pulltorefresh.PullToRefreshBase;
import com.view.pulltorefresh.PullToRefreshScrollView;

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class BoutiquePage extends BaseFragment {
    private ViewPager viewPager;
    private static final int GETBANNERSUCCES = 0;
    private static final int GETBANNERFAIL = 1;
    private static final int SCROLLBANNER = 4;
    private static final int PAUSESCROLLBANNER = 5; //请求暂停banner图片自动轮播
    private static final int GETNOTICESUCCES = 6;
    private static final int GETNOTICEFAIL = 7;

    private static final int GETPLATINFOQUERYSUC = 8;
    private static final int GETPLATINFOQUERYFAIL = 9;
    private static final int TJREGISTQUERYSUC = 10;
    private static final int TJREGISTQUERYFAIL = 11;
    private static final int TJPROXQUERYSUC = 12;
    private static final int TJPROXQUERYFAIL = 13;
    private final static int OPEN_PAYMENT_SUCESS = 14;
    private final static int OPEN_PAYMENT_FAIL = 15;
    private static final int OPENAUTOCURRENTPROJECTSUCCES = 16;
    private static final int OPENAUTOCURRENTPROJECTFAIL = 17;
    private static final int TJPROQUERYSUC = 18;
    private static final int TJPROQUERYFAIL = 19;

    private static final int GETDETAILSUCCES = 20;
    private static final int GETDETAILFAIL = 21;

    private List<Banner> imageIdList;
    private ImagePagerAdapter imagePagerAdapter;
    private HashMap<String, String> params;
    private BaseHandler handler;
    private HomeActivity activity;
    private ProjectdetailData choiceproject;
    private List<Banner> banners;
    private long sleeptime = 4000;
    private PullToRefreshScrollView imager_pager_sc;
    private LinearLayout ll_vp; //盛放indicator的容器相当于

    int count = 0;
    private LinearLayout choiceproject_layout; //普通项目的布局
    private LinearLayout experience_layout; //万元体验金布局
    private TextView tv_experience_interest;
    private TextView tv_experience_amount;
    private TextView tv_experience_tips;
    private Button btn_experience_get;
    private List<Notice> listNotice;
    private RelativeLayout rl_boutique_notice;
    private ImageView iv_tonotice;
    private ViewPager view_pager_notice;
    private TextView tv_1;
    private TextView tv_all_person;
    private TextView tv_2;
    private TextView tv_all_amount;
    private TextView tv_unit;
    private TextView tv_unit_left;
    private RelativeLayout rl_one;
    private ImageView iv_1;
    private TextView tv_one;
    private RelativeLayout rl_two;
    private ImageView iv_2;
    private TextView tv_two;
    private RelativeLayout rl_three;
    private ImageView iv_3;
    private TextView tv_three;
    private RelativeLayout rl_four;
    private ImageView iv_4;
    private TextView tv_four;
    private BitmapUtils bitmapUtils;

    private List<PlatInfoTwo> platInfoTwoList;
    private LinearLayout ll_newer;
    private TextView tv_newer_title;
    private TextView tv_newer_content;
    private Button btn_newer;
    private TextView tv_title, tv_current_interest, tv_income_day;
    private Button btn_buy_current;
    private LinearLayout ll_current;
    private View layout_newer;
    private View layout_project;
    private View layout_current;
    private TjRegisteResult mTjRegisteResult;
    private TextView tv_mortgage_type;
    private TextView project_name_tv;
    private TextView project_active;
    private TextView project_yield_tv;
    private TextView project_period_tv;
    private TextView project_amount_tv;
    private Button btn_buy;
    private RelativeLayout rl_timer_count;
    private TextView timer_val;
    private TextView timer_pre;
    private NoticeAdapter mNoticeAdapter;
    private ProjectCommingJob projectCommingJob;

    @Override
    protected View loadViewLayout(LayoutInflater inflater, ViewGroup container) {
        View v = inflater.inflate(R.layout.main_page_layout, container, false);
        activity = (HomeActivity) getActivity();
        return v;
    }

    @Override
    protected void findViewById(View view) {
        viewPager = (ViewPager) view.findViewById(R.id.view_pager);
        imager_pager_sc = (PullToRefreshScrollView) view.findViewById(R.id.imager_pager_sc);
        ll_vp = (LinearLayout) view.findViewById(R.id.ll_vp);
        rl_boutique_notice = (RelativeLayout) view.findViewById(R.id.rl_boutique_notice);
        iv_tonotice = (ImageView) view.findViewById(R.id.iv_tonotice);
        view_pager_notice = (ViewPager) view.findViewById(R.id.view_pager_notice);

        tv_1 = (TextView) view.findViewById(R.id.tv_1);
        tv_all_person = (TextView) view.findViewById(R.id.tv_all_person);
        tv_2 = (TextView) view.findViewById(R.id.tv_2);
        tv_all_amount = (TextView) view.findViewById(R.id.tv_all_amount);
        tv_unit = (TextView) view.findViewById(R.id.tv_unit);
        tv_unit_left = (TextView) view.findViewById(R.id.tv_unit_left);

        rl_one = (RelativeLayout) view.findViewById(R.id.rl_one);
        iv_1 = (ImageView) view.findViewById(R.id.iv_1);
        tv_one = (TextView) view.findViewById(R.id.tv_one);
        rl_two = (RelativeLayout) view.findViewById(R.id.rl_two);
        iv_2 = (ImageView) view.findViewById(R.id.iv_2);
        tv_two = (TextView) view.findViewById(R.id.tv_two);
        rl_three = (RelativeLayout) view.findViewById(R.id.rl_three);
        iv_3 = (ImageView) view.findViewById(R.id.iv_3);
        tv_three = (TextView) view.findViewById(R.id.tv_three);
        rl_four = (RelativeLayout) view.findViewById(R.id.rl_four);
        iv_4 = (ImageView) view.findViewById(R.id.iv_4);
        tv_four = (TextView) view.findViewById(R.id.tv_four);

        layout_newer = view.findViewById(R.id.layout_newer);
        layout_project = view.findViewById(R.id.layout_project);
        layout_current = view.findViewById(R.id.layout_current);

        findViewByIdOfNewer(view);
        findViewByIdOfProject(view);
        findViewByIdOfCurrent(view);

        findViewByIdOfExperience(view); //初始化万元体验金的布局id
    }

    private void findViewByIdOfCurrent(View view) {
        ll_current = (LinearLayout) view.findViewById(R.id.ll_current);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_current_interest = (TextView) view.findViewById(R.id.tv_current_interest);
        tv_income_day = (TextView) view.findViewById(R.id.tv_income_day);
        btn_buy_current = (Button) view.findViewById(R.id.btn_buy_current);

    }

    private void findViewByIdOfProject(View view) {
        project_name_tv = (TextView) view.findViewById(R.id.project_name_tv); //migncheng
        project_active = (TextView) view.findViewById(R.id.project_active);
        project_amount_tv = (TextView) view.findViewById(R.id.project_amount_tv);
        project_yield_tv = (TextView) view.findViewById(R.id.project_yield_tv);
        timer_pre = (TextView) view.findViewById(R.id.timer_pre);
        timer_val = (TextView) view.findViewById(R.id.timer_val);
        rl_timer_count = (RelativeLayout) view.findViewById(R.id.rl_timer_count);
        project_period_tv = (TextView) view.findViewById(R.id.project_period_tv);
        tv_mortgage_type = (TextView) view.findViewById(R.id.tv_mortgage_type); //leixing
        btn_buy = (Button) view.findViewById(R.id.btn_buy);
    }

    private void findViewByIdOfNewer(View view) {
        ll_newer = (LinearLayout) view.findViewById(R.id.ll_newer);
        tv_newer_title = (TextView) view.findViewById(R.id.tv_newer_title);
        tv_newer_content = (TextView) view.findViewById(R.id.tv_newer_content);
        btn_newer = (Button) view.findViewById(R.id.btn_newer);
    }

    private void findViewByIdOfExperience(View view) {
        choiceproject_layout = (LinearLayout) view.findViewById(R.id.choiceproject_layout);
        experience_layout = (LinearLayout) view.findViewById(R.id.experience_layout);
        tv_experience_interest = (TextView) view.findViewById(R.id.tv_experience_interest);
        tv_experience_amount = (TextView) view.findViewById(R.id.tv_experience_amount);
        tv_experience_tips = (TextView) view.findViewById(R.id.tv_experience_tips);
        btn_experience_get = (Button) view.findViewById(R.id.btn_experience_get);
        btn_experience_get.setOnClickListener(this);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) { //从显示切换到不显示
            if (imager_pager_sc != null) {
                imager_pager_sc.scrollToTop();
            }
            handler.removeCallbacksAndMessages(null);
        } else {
            if (imager_pager_sc != null) {
                imager_pager_sc.scrollToTop();
            }
            getchoiceproject(); //获取精选项目
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.iv_tonotice:
                Notice currentNotice = mNoticeAdapter.getCurrentNotice(view_pager_notice
                        .getCurrentItem());
                if (currentNotice != null && !StringUtils.isEmpty(currentNotice.getId())) {
                    Intent intent = new Intent(mactivity, WebViewPage.class);
                    intent.putExtra("title", currentNotice.getTitle());
                    Map<String, String> contractmap = new HashMap<String, String>();
                    contractmap.put("id", currentNotice.getId());
                    intent.putExtra("url",
                            Constants.NOTICEINFOHTML + "?" + URLUtil.createContractUrl(contractmap, "3.0"));

                    startnewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                }
                break;
            //        case R.id.layout_newer:
            case R.id.btn_newer:
                if (mTjRegisteResult != null) {
                    //                Intent intent1 = new Intent(getActivity(), RegisterPage.class);
                    //                startnewActivity(intent1, R.anim.slide_in_from_bottom, R.anim.silent_anim, false);
                    Intent intent1 = new Intent(getActivity(), LoginPage.class);
                    intent1.putExtra("witchLayout", "regist");
                    startnewActivity(intent1, R.anim.slide_in_from_bottom, R.anim.silent_anim, false);
                }
                break;
            case R.id.rl_one:
                if (platInfoTwoList != null) {
                    ConstantDataUnit xsrm = mactivity.getConstantDataByKey(platInfoTwoList.get(0)
                            .getKey());
                    if (xsrm != null) {
                        Intent int1 = new Intent(mactivity, WebViewPage.class);
                        int1.putExtra("url", xsrm.getVal());
                        int1.putExtra("title", platInfoTwoList.get(0).getName());
                        startnewActivity(int1, R.anim.push_left_in, R.anim.push_left_out, false);
                    }
                }
                break;
            case R.id.rl_two:
                if (platInfoTwoList != null) {
                    ConstantDataUnit ptsj = mactivity.getConstantDataByKey(platInfoTwoList.get(1)
                            .getKey());
                    if (ptsj != null) {
                        Intent int1 = new Intent(mactivity, WebViewPage.class);
                        int1.putExtra("url", ptsj.getVal());
                        int1.putExtra("title", platInfoTwoList.get(1).getName());
                        startnewActivity(int1, R.anim.push_left_in, R.anim.push_left_out, false);
                    }
                }
                break;
            case R.id.rl_three:
                if (platInfoTwoList != null) {
                    ConstantDataUnit aqbz = mactivity.getConstantDataByKey(platInfoTwoList.get(2)
                            .getKey());
                    if (aqbz != null) {
                        Intent int1 = new Intent(mactivity, WebViewPage.class);
                        int1.putExtra("url", aqbz.getVal());
                        int1.putExtra("title", platInfoTwoList.get(2).getName());
                        startnewActivity(int1, R.anim.push_left_in, R.anim.push_left_out, false);
                    }
                }
                break;
            case R.id.rl_four:
                if (platInfoTwoList != null) {
                    ConstantDataUnit gywm = mactivity.getConstantDataByKey(platInfoTwoList.get(3)
                            .getKey());
                    if (gywm != null) {
                        Intent int1 = new Intent(mactivity, WebViewPage.class);
                        int1.putExtra("url", gywm.getVal());
                        int1.putExtra("title", platInfoTwoList.get(3).getName());
                        startnewActivity(int1, R.anim.push_left_in, R.anim.push_left_out, false);
                    }
                }
                break;
            case R.id.btn_experience_get: //万元体验金跳到他专属的详情页去
                if (ViewUtils.isFastDoubleClick(view)) {
                    return;
                }
                if (choiceproject != null) {}
                break;
            default:
                break;
        }

    }

    @Override
    protected void setListener() {
        rl_one.setOnClickListener(this);
        rl_two.setOnClickListener(this);
        rl_three.setOnClickListener(this);
        rl_four.setOnClickListener(this);
        layout_newer.setOnClickListener(this);
        layout_project.setOnClickListener(this);
        layout_current.setOnClickListener(this);
        btn_newer.setOnClickListener(this);

        handler = new BaseHandler(activity) {

            @Override
            public void handleMessage(Message msg) {

                //检查消息队列并移除未发送的消息，这主要是避免消息出现重复等问题。  
                if (handler.hasMessages(SCROLLBANNER)) {
                    handler.removeMessages(SCROLLBANNER);
                }

                switch (msg.what) {

                    case GETDETAILSUCCES:
                        Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                        if (result.isOk()) {
                            ProjectdetailData ttt = JSON.parseObject(result.data,
                                    ProjectdetailData.class);
                            ProjectdetailData pDetail = ttt;
                            if (pDetail.getAmount() != 0) {
                                Order order = new Order();
                                order.setProjectid(pDetail.getProjectId());
                                order.setProjectname(pDetail.getName());
                                order.setProject_yield(pDetail.getYield() + pDetail.getAwardYield());
                                order.setRecyle(pDetail.getPeriod());
                                order.setRepaymenttype(pDetail.getRepayTypeName());
                                order.setStartrepytime(pDetail.getEndInterestDate());
                                order.setStartyidtime(pDetail.getStartInterestDate());
                                order.setCaninverst(Double.parseDouble(pDetail.getRemainAmount()));
                                order.setpType(pDetail.getpType());
                                order.setMinInvest(pDetail.getMinInvest());
                                order.setMaxInvest(pDetail.getMaxInvest());

                                order.setType(pDetail.getType());
                                order.setMode(pDetail.getMode());

                                Intent intent = new Intent(mactivity, InverstInputAmountPage.class)
                                        .putExtra("ORDER", order);
                                startnewActivity(intent, R.anim.slide_in_from_bottom,
                                        R.anim.silent_anim, false);
                            }
                        } else {
                            showToast(result.codeDesc);
                        }
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);

                        break;
                    case GETDETAILFAIL:
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case OPENAUTOCURRENTPROJECTSUCCES:
                        Basebean result_o = JSONObject.parseObject((String) msg.obj, Basebean.class);
                        if (result_o.isOk()) {
                            BroswerUrl url = JSONObject.parseObject(result_o.data, BroswerUrl.class);
                            Intent intent = new Intent(mactivity, WebViewPage.class);
                            intent.putExtra("title", "账户自动投资");
                            intent.putExtra("url", url.getUrl());
                            intent.putExtra("BUSINESS_TYPE", WebViewPage.TYPE_OPEN_AUTO_PROJECT);
                            startnewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                        } else {
                            showToast(result_o.codeDesc);
                        }
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case OPENAUTOCURRENTPROJECTFAIL:
                        showToast("网络不佳，请重试");
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case OPEN_PAYMENT_SUCESS:
                        Basebean result_open = JSONObject.parseObject((String) msg.obj, Basebean.class);
                        if (result_open.isOk()) {
                            Intent in = new Intent();
                            BroswerUrl responseinfo = JSON.parseObject(result_open.data,
                                    BroswerUrl.class);
                            in.setClass(mactivity, WebViewPage.class).putExtra("title", "汇付天下托管账号")
                                    .putExtra("url", responseinfo.getUrl())
                                    .putExtra("BUSINESS_TYPE", WebViewPage.TYPE_PAYMENT_REGIST);
                            startnewActivity(in, R.anim.push_left_in, R.anim.push_left_out, false);
                        }
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case OPEN_PAYMENT_FAIL:
                        showToast("网络不佳，请重试");
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case GETBANNERSUCCES: //banner
                        Basebean result_banner = JSON.parseObject((String) msg.obj, Basebean.class);
                        if (result_banner.isOk()) {
                            imager_pager_sc.getLoadingLayoutProxy().setLastUpdatedLabel(
                                    "最后更新：今天 " + TimeUtils.getFormatDate(" HH:mm"));
                            DataList dataList = JSONObject.parseObject(result_banner.data,
                                    DataList.class);
                            banners = JSONArray.parseArray(dataList.getList(), Banner.class);
                            imageIdList.removeAll(imageIdList);
                            imageIdList.addAll(banners);
                            imagePagerAdapter = new ImagePagerAdapter(activity, banners);
                            if (imagePagerAdapter != null) {
                                viewPager.setAdapter(imagePagerAdapter);
                            }

                            handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                            ll_vp.removeAllViews();//下拉会重新请求banner图接口。所以将所有的小圆点移除

                            for (int i = 0; i < imageIdList.size(); i++) {

                                // 添加点了
                                ImageView point = new ImageView(activity);
                                // 创建了布局的参数 全部都是包裹内容
                                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-2, -2);
                                params.leftMargin = 5;
                                // 给ImageView 设置参数
                                point.setLayoutParams(params);
                                point.setImageResource(R.drawable.selectot_points);
                                if (i == 0) {
                                    count = 0;
                                    point.setEnabled(true);
                                } else {
                                    point.setEnabled(false);
                                }
                                ll_vp.addView(point);
                            }
                        }
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case GETBANNERFAIL:
                        showToast("网络不佳，请重试");
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case TJPROQUERYSUC: //定期推荐
                        Basebean result_tjpro = JSON.parseObject((String) msg.obj, Basebean.class);
                        if (result_tjpro.isOk()) {
                            final ProjectDetail mProjectDetail = JSONObject.parseObject(
                                    result_tjpro.data, ProjectDetail.class);
                            if (mProjectDetail == null) {
                                return;
                            }
                            tv_mortgage_type.setText(mProjectDetail.getPledgeType());
                            project_name_tv.setText(mProjectDetail.getName() + "");
                            if (mProjectDetail.getActivityMark() == 0) {
                                project_active.setVisibility(View.GONE);
                            } else {
                                project_active.setVisibility(View.VISIBLE);
                                project_active.setText(mProjectDetail.getActivityName());
                            }
                            project_yield_tv.setText(ArithUtils.formatProject(
                                    mProjectDetail.getYield(), "#.#") + "");
                            project_period_tv.setText(mProjectDetail.getPeriod() + "");
                            project_amount_tv.setText(ArithUtils.coverMoneyComma(mProjectDetail
                                    .getRemainAmount()));
                            switch (mProjectDetail.getStatus()) {
                                case Constants.PRO_STATUS_WAITING: // 未开始（初审通过/待上架）
                                    rl_timer_count.setVisibility(View.VISIBLE);
                                    timer_val.setText(mProjectDetail.getTime2Start());
                                    btn_buy.setText("立即抢购");
                                    btn_buy.setEnabled(false);
                                    if (projectCommingJob == null) {
                                        projectCommingJob = new ProjectCommingJob(mProjectDetail);
                                        projectCommingJob.start();
                                    } else {
                                        projectCommingJob.stop();
                                        projectCommingJob = new ProjectCommingJob(mProjectDetail);
                                        projectCommingJob.start();
                                    }

                                    project_amount_tv.setTextColor(mactivity.getResources().getColor(
                                            color.gray_2));
                                    break;
                                case Constants.PRO_STATUS_TRADING: // 募集中（已上架/融资中）
                                    rl_timer_count.setVisibility(View.GONE);
                                    btn_buy.setText("立即抢购");
                                    btn_buy.setEnabled(true);
                                    project_amount_tv.setTextColor(mactivity.getResources().getColor(
                                            color.gray_2));
                                    break;
                                case Constants.PRO_STATUS_FULFILL: // 募集完成（ 已满标/待复审）
                                case Constants.PRO_STATUS_CHECK_WAIT: // 募集完成（复审通过/数据处理中）
                                    rl_timer_count.setVisibility(View.GONE);
                                    btn_buy.setText(mProjectDetail.getStatusName() + "");
                                    btn_buy.setEnabled(false);
                                    project_amount_tv.setTextColor(mactivity.getResources().getColor(
                                            color.gray_1));
                                    break;
                                case Constants.PRO_STATUS_CHECKED: // 还款中（复审通过/还款中）
                                case Constants.PRO_STATUS_REPAYING: // 还款中（还款中/数据处理中）；
                                case Constants.PRO_STATUS_REPAYMENT_EARLY: // 还款中（提前还款）
                                    rl_timer_count.setVisibility(View.GONE);
                                    btn_buy.setText(mProjectDetail.getStatusName() + "");
                                    btn_buy.setEnabled(false);

                                    project_amount_tv.setTextColor(mactivity.getResources().getColor(
                                            color.gray_1));
                                    break;
                                case Constants.PRO_STATUS_REPAYMENT: //已还款（正常还款）
                                case Constants.PRO_STATUS_REPAYMENT_LATE: // 已还款（逾期还款）
                                    rl_timer_count.setVisibility(View.GONE);
                                    btn_buy.setText(mProjectDetail.getStatusName() + "");
                                    btn_buy.setEnabled(false);
                                    project_amount_tv.setTextColor(mactivity.getResources().getColor(
                                            color.gray_1));
                                    break;
                                case Constants.PRO_STATUS_LATE: // 逾期（逾期）
                                    rl_timer_count.setVisibility(View.GONE);
                                    btn_buy.setText(mProjectDetail.getStatusName() + "");
                                    btn_buy.setEnabled(false);
                                    project_amount_tv.setTextColor(mactivity.getResources().getColor(
                                            color.gray_1));
                                    break;
                            }

                            layout_project.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(mactivity, ProjectDetailPage.class)
                                            .putExtra("PROJECT_ID", mProjectDetail.getProjectId())
                                            .putExtra("MODE", mProjectDetail.getMode());
                                    mactivity.startNewActivity(intent, R.anim.push_left_in,
                                            R.anim.push_left_out, false);
                                }
                            });

                            btn_buy.setOnClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    if (mProjectDetail.getStatus() != Constants.PRO_STATUS_TRADING) {
                                        return;
                                    }
                                    if (Constants.PRO_TYPE_NEWER.equals(mProjectDetail.getMode())) { //新手项目非新手不可点
                                        if (!mactivity.isNewMan()) {
                                            mactivity.showToast("新手项目仅限第一次投资");
                                            return;
                                        }
                                    }
                                    getProjectDetail(mProjectDetail.getProjectId(),
                                            mProjectDetail.getMode());
                                }

                            });
                        }
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        imager_pager_sc.onRefreshComplete();
                        break;
                    case TJPROQUERYFAIL:
                        showToast("网络不佳，请重试");
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case TJPROXQUERYSUC: //活期推荐
                        Basebean result_tjprox = JSON.parseObject((String) msg.obj, Basebean.class);
                        if (result_tjprox.isOk()) {
                            final CurrentProject mCurrentProject = JSONObject.parseObject(
                                    result_tjprox.data, CurrentProject.class);
                            tv_title.setText(mCurrentProject.getTitle());
                            tv_current_interest.setText(ArithUtils.coverMoney(mCurrentProject
                                    .getCompoundYield() + ""));
                            tv_income_day.setText(ArithUtils.coverMoneyFour(mCurrentProject
                                    .getInterestUnits() + ""));
                            layout_current.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mactivity.startNewActivity(
                                            new Intent(mactivity, HomeActivity.class).putExtra("BUTTON",
                                                    R.id.radio_btn3), R.anim.push_left_in,
                                            R.anim.push_left_out, false);
                                }
                            });
                            btn_buy_current.setOnClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    if (!TwoTigerApp.getInstance().getUser().hasOpenThirdAct) {
                                        PromptManager.showConfirmAlertCommon(mactivity, 0, "",
                                                "您还未开通汇付天下托管账号，继续开通", "取消", "继续", true,
                                                new ReChargeClickListener() {

                                                    @Override
                                                    public void onClickConfirm() {

                                                    }

                                                    @Override
                                                    public void onClickCancel() {
                                                        // 确认，则继续
                                                        params.clear();
                                                        params.put("token", getToken());
                                                        mactivity.getDate(params, Constants.REGISTHF,
                                                                handler, OPEN_PAYMENT_SUCESS,
                                                                OPEN_PAYMENT_FAIL, true, true, false);
                                                    }
                                                });

                                        return;
                                    }
                                    if (TwoTigerApp.getInstance().getUser().hasOpenProjectXAct) {
                                        Intent intent2 = new Intent(mactivity,
                                                CurrentInputAmountPage.class);
                                        intent2.putExtra("CURRENTPROJECT", mCurrentProject);
                                        mactivity.startNewActivityforresult(intent2,
                                                R.anim.slide_in_from_bottom, R.anim.silent_anim,
                                                CurrentHost.CURRENTREQUEST);
                                    } else {
                                        PromptManager.showCurrentAlertHasBtn(mactivity, "",
                                                "参与老虎活期，需要您授权开通账户自动投资功能。\n自动投资将仅用于活期每日复投，不会影响到其他资金。",
                                                "立即开通", false, new ReChargeClickListener() {

                                                    @Override
                                                    public void onClickConfirm() {
                                                        openAutoCurrentProject();
                                                    }

                                                    @Override
                                                    public void onClickCancel() {

                                                    }
                                                });
                                    }
                                }
                            });
                        } else {
                            showToast(result_tjprox.codeDesc);
                        }
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        imager_pager_sc.onRefreshComplete();
                        break;
                    case TJPROXQUERYFAIL:
                        showToast("网络不佳，请重试");
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case TJREGISTQUERYSUC:
                        Basebean result_tjregist = JSON.parseObject((String) msg.obj, Basebean.class);
                        if (result_tjregist.isOk()) {
                            mTjRegisteResult = JSONObject.parseObject(result_tjregist.data,
                                    TjRegisteResult.class);
                            tv_newer_title.setText(mTjRegisteResult.getTitle());
                            tv_newer_content.setText(mTjRegisteResult.getContent());
                        } else {
                            showToast(result_tjregist.codeDesc);
                        }
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        imager_pager_sc.onRefreshComplete();
                        break;
                    case TJREGISTQUERYFAIL:
                        showToast("网络不佳，请重试");
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case GETPLATINFOQUERYSUC:
                        Basebean result_platinfo = JSON.parseObject((String) msg.obj, Basebean.class);
                        if (result_platinfo.isOk()) {
                            PlatInfo platinfo = JSONObject.parseObject(result_platinfo.data,
                                    PlatInfo.class);
                            List<PlatInfoOne> platInfoOneList = JSONArray.parseArray(
                                    platinfo.getListOne(), PlatInfoOne.class);
                            if (!ListUtils.isEmpty(platInfoOneList)) {
                                tv_1.setText(platInfoOneList.get(0).getName());
                                tv_all_person.setText(ArithUtils.coverMoneyCommaNoSmall(platInfoOneList
                                        .get(0).getVal()));
                                tv_unit_left.setText(platInfoOneList.get(0).getUnit());
                                tv_2.setText(platInfoOneList.get(1).getName());
                                tv_all_amount.setText(ArithUtils.coverMoneyComma(platInfoOneList.get(1)
                                        .getVal()));
                                tv_unit.setText(platInfoOneList.get(1).getUnit());
                            }
                            platInfoTwoList = JSONArray.parseArray(platinfo.getListTwo(),
                                    PlatInfoTwo.class);
                            if (!ListUtils.isEmpty(platInfoTwoList)) {
                                bitmapUtils.display(iv_1, Constants.HOST
                                        + platInfoTwoList.get(0).getImgUrl());
                                tv_one.setText(platInfoTwoList.get(0).getName());

                                bitmapUtils.display(iv_2, Constants.HOST
                                        + platInfoTwoList.get(1).getImgUrl());
                                tv_two.setText(platInfoTwoList.get(1).getName());

                                bitmapUtils.display(iv_3, Constants.HOST
                                        + platInfoTwoList.get(2).getImgUrl());
                                tv_three.setText(platInfoTwoList.get(2).getName());

                                bitmapUtils.display(iv_4, Constants.HOST
                                        + platInfoTwoList.get(3).getImgUrl());
                                tv_four.setText(platInfoTwoList.get(3).getName());

                            }
                        } else {
                            showToast(result_platinfo.codeDesc);
                        }
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        imager_pager_sc.onRefreshComplete();
                        break;
                    case GETPLATINFOQUERYFAIL:
                        showToast("网络不佳，请重试");
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case GETNOTICESUCCES:
                        Basebean result_notice = JSON.parseObject((String) msg.obj, Basebean.class);
                        if (result_notice.isOk()) {
                            DataList noticeList = JSONObject.parseObject(result_notice.data,
                                    DataList.class);
                            listNotice = JSONArray.parseArray(noticeList.getList(), Notice.class);
                            if (!ListUtils.isEmpty(listNotice)) {
                                rl_boutique_notice.setVisibility(View.VISIBLE);
                                mNoticeAdapter = new NoticeAdapter(mactivity, listNotice);
                                view_pager_notice.setAdapter(mNoticeAdapter);
                            } else {
                                rl_boutique_notice.setVisibility(View.GONE);
                            }
                        }
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        imager_pager_sc.onRefreshComplete();
                        break;
                    case GETNOTICEFAIL:
                        showToast("网络不佳，请重试");
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case SCROLLBANNER:
                        if (banners != null && !banners.isEmpty()) {
                            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                            if (!ListUtils.isEmpty(listNotice) && listNotice.size() > 1) {
                                view_pager_notice
                                        .setCurrentItem(view_pager_notice.getCurrentItem() + 1);
                            }
                        }
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case PAUSESCROLLBANNER:
                        //不做任何操作，即不发送消息，他就不再轮播了
                        break;
                    default:
                        break;
                }
                super.handleMessage(msg);
            }
        };
        //        rl_boutique_notice.setOnClickListener(this);
        iv_tonotice.setOnClickListener(this);
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {
            //复写该方法，实现viewpager对应圆点的变化
            @Override
            public void onPageSelected(int position) {
                if (imageIdList.size() > 0) {
                    int index = position % imageIdList.size();
                    // 获得了之前的点
                    ImageView last_point = (ImageView) ll_vp.getChildAt(count);
                    if (last_point != null) {
                        last_point.setEnabled(false);
                    }
                    // 现在的点 高亮显示
                    ImageView point = (ImageView) ll_vp.getChildAt(index);
                    if (point != null) {
                        point.setEnabled(true);
                    }

                    count = index;
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            //复写该方法实现viewpager轮播的暂停和恢复
            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_IDLE: //未手动
                        handler.sendEmptyMessageDelayed(SCROLLBANNER, sleeptime);
                        break;
                    case ViewPager.SCROLL_STATE_DRAGGING: //手动滑动
                        handler.sendEmptyMessage(PAUSESCROLLBANNER);
                        break;

                    default:
                        break;
                }
            }
        });

        imager_pager_sc
                .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {

                    @Override
                    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                        getchoiceproject();
                    }

                    @Override
                    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                    }
                });
    }

    //请求直投的项目详情
    public void getProjectDetail(String proId, String mode) {
        params.clear();
        params.put("projectId", proId);
        params.put("type", Constants.TYPE_NID_ZHITOU);
        params.put("mode", mode);
        params.put("token", getToken());
        mactivity.getDate(params, Constants.PROJECTINFOQUERY, handler, GETDETAILSUCCES,
                GETDETAILFAIL, true, true, true);
    }

    private void openAutoCurrentProject() {
        params.clear();
        params.put("token", getToken());
        mactivity.getDate(params, Constants.PROJECTXOPEN, handler, OPENAUTOCURRENTPROJECTSUCCES,
                OPENAUTOCURRENTPROJECTFAIL, true, false, false);
    }

    @SuppressLint("InlinedApi")
    @Override
    protected void processLogic() {
        bitmapUtils = new BitmapUtils(mactivity);
        params = activity.getParm();
        getchoiceproject(); //获取精选项目
        viewPager.setAdapter(new ImagePagerAdapter(activity, null));
    }

    private void getBanner() {
        params.clear();
        activity.getDate(params, Constants.BANNERQUERY, handler, GETBANNERSUCCES, GETBANNERFAIL,
                false, false, true);
        imageIdList = new ArrayList<Banner>();
    }

    /**
     * 获取token
     * @return
     */

    public String getToken() {
        return TwoTigerApp.getInstance().getUser().token;
    }

    private void getchoiceproject() {
        //判断显示哪个布局  未登录、未投资和投资
        if (!mactivity.isLogin()) {
            layout_newer.setVisibility(View.VISIBLE);
            layout_project.setVisibility(View.GONE);
            layout_current.setVisibility(View.GONE);

            params.clear();
            activity.getDate(params, Constants.TJREGISTQUERY, handler, TJREGISTQUERYSUC,
                    TJREGISTQUERYFAIL, false, false, false);
        } else {
            if ((!mactivity.application.getUser().isHasProject())
                    && (!mactivity.application.getUser().isHasProjectX())) {
                layout_newer.setVisibility(View.GONE);
                layout_project.setVisibility(View.GONE);
                layout_current.setVisibility(View.VISIBLE);

                params.clear();
                params.put("token", getToken());
                activity.getDate(params, Constants.TJPROXQUERY, handler, TJPROXQUERYSUC,
                        TJPROXQUERYFAIL, false, false, false);

            } else {
                layout_newer.setVisibility(View.GONE);
                layout_project.setVisibility(View.VISIBLE);
                layout_current.setVisibility(View.GONE);

                getJproquery();
            }
        }

        params.clear();
        params.put("token", getToken());
        activity.getDate(params, Constants.PLATINFOQUERY, handler, GETPLATINFOQUERYSUC,
                GETPLATINFOQUERYFAIL, false, false, false);

        params.clear();
        activity.getDate(params, Constants.NOTICEQUERY, handler, GETNOTICESUCCES, GETNOTICEFAIL,
                false, false, false);

        getBanner();
    }

    private void getJproquery() {
        params.clear();
        params.put("token", getToken());
        activity.getDate(params, Constants.TJPROQUERY, handler, TJPROQUERYSUC, TJPROQUERYFAIL,
                false, false, false);
    }

    @Override
    public boolean isNeedLogin() {
        return false;
    }

    @Override
    public void rebuildTitleStyle() {
        subTitle.setBgResource(R.drawable.bg_common_title).setTitle(getTitle()).setLeftName("")
                .setRightName("").setColor(Color.WHITE).hideBtns().hideBottomLine();
        mactivity.tintManager.setTintResource(R.drawable.bg_common_statusbar);
        mactivity.setLayoutPadding(false);
    }

    @Override
    public String getTitle() {
        return "两只老虎";
    }

    @Override
    public void reLoadData() {
    }

    /**
     * 项目倒计时job
     * @Description:
     * 生命周期,start--->stop必须销毁 
     * @Author douxy
     * @Date 2015年8月18日 下午12:57:25
     */
    class ProjectCommingJob implements Runnable {

        /**每个县城只能start一次*/
        private boolean isRun = false;
        private boolean stop = false;

        private ProjectDetail projectDetail;

        public ProjectCommingJob(ProjectDetail mProjectDetail) {
            this.projectDetail = mProjectDetail;
        }

        public void stop() {
            this.stop = true;
        }

        public void start() {
            if (isRun)
                return;
            isRun = true;
            stop = false;
            handler.post(this);
        }

        @Override
        public void run() {
            if (!"即将开始".equals(projectDetail.getTime2Start())) {
                timer_val.setText("" + projectDetail.getTime2Start());
            } else {
                getJproquery();
                stop();
            }
            if (stop) {
                return;
            }
            handler.postDelayed(this, 1000);
        }
    }

}
